package kr.hkit.androidcomplete02.ch16;

import java.util.ArrayList;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class CheckQuestionFrg extends Activity implements CheckDialogFragment.NoticeDialogListener{
	TextView tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch16_dialog);
		tv = (TextView) findViewById(R.id.textView1);
	}
	
	public void mOnClick(View v){
		CheckDialogFragment listFrg = new CheckDialogFragment();
		listFrg.show(getFragmentManager(), "dialog");
	}

	@Override
	public void onDialogClick(DialogFragment frg, String res) {
		tv.setText("선택한 과일은 " + res);
	}
}

class CheckDialogFragment extends DialogFragment{
	NoticeDialogListener mListener;
	ArrayList<Integer> mSelects = new ArrayList<>();
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try{
			mListener = (NoticeDialogListener) activity;
		}catch(ClassCastException e){
			Log.d("ClassCastException", activity.toString() + "NoticeDialogListener를 구현");
		}
	}
	
	public interface NoticeDialogListener{
		public void onDialogClick(DialogFragment frg, String res);
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		return new AlertDialog.Builder(getActivity())
				.setTitle("음식을 선택하시오")
				.setIcon(R.drawable.ic_launcher)
				.setMultiChoiceItems(R.array.fruits, null, new OnMultiChoiceClickListener() {
					public void onClick(DialogInterface dialog, int which, boolean isChecked) {
						Toast.makeText(getActivity(), "which" + which, 3).show();
						if (isChecked){
							mSelects.add(which);
						}else if(mSelects.contains(which)){
							mSelects.remove(mSelects.indexOf(which));
						}
					}
				})
				.setPositiveButton("확인", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String[] fruits = getResources().getStringArray(R.array.fruits);
						StringBuilder sb = new StringBuilder();
						for(int idx:mSelects){
							sb.append(fruits[idx]+", ");
						}
						sb.delete(sb.length()-2, sb.length()-1);
						mListener.onDialogClick(CheckDialogFragment.this, sb.toString());
					}
				})
				.setNegativeButton("취소", null)
				.create();
				
	}
}
